# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2011 ZestyBeanz Technologies Pvt. Ltd.
#    (http://wwww.zbeanztech.com) All Rights Reserved.
#     vishnu@zbeanztech.com
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields,osv
from tools.translate import _
import pooler
from email.Utils import COMMASPACE
import time

class mail_group(osv.osv):
    _name = "mail.group"
    _description = "Mail Group"
    _columns = {
                'name': fields.char('Name', size=60, required=True),
                'member_ids': fields.one2many('mail.group.member', 'mail_group_id', 'Members'),
                'seq_ids': fields.one2many('mail.sequence', 'mail_group_id', 'Sequences'),
                'history_ids':fields.one2many('mail.history', 'mail_group_id', 'History',readonly=True),
                }



    def send_mail(self, cr, uid, ids, filtered_users=[], sub="", cc=[]):
        pool = self.pool
        result=None
        context=None


        smtp = self.pool.get('email.smtpclient')
        smtpserver_id = self.pool.get('email.smtpclient').select(cr, uid, 'massmail')

        email=[]
        subject=''
        template_id=''
        history={}
        for grp in self.browse(cr, uid, ids):
            if grp.member_ids:
                for member in grp.member_ids:
                    #if member.partner_id and member.partner_id.address and member.partner_id.address[0].email:
                    if member.email:
                        to=member.email
                        partner=member.prospect

                    if smtpserver_id is False:
                        raise Exception, _('Please check the Server Configuration!')

                    for seq in grp.seq_ids:
                        template_id=seq.template_id.id
                        subject=seq.template_id.name
                        body=False
                        template=self.pool.get('email.smtpclient.email.template').browse(cr, uid,[template_id])
                        body=template[0].body

                        smtpserver = self.pool.get('email.smtpclient').browse(cr, uid, smtpserver_id, context=False)
                        email=COMMASPACE.join([to])



                        body = (body or smtpserver.body) or ''
                        body = body and body.replace('__partner__', partner or '')

                        current_time=time.strftime('%Y-%m-%d')


                        if seq.state=='draft' and seq.next_call and seq.next_call<current_time:
                            self.pool.get('mail.sequence').write(cr,uid,[seq.id],{'state':'pending'})
                        if seq.state=='draft' and seq.next_call and seq.next_call<=current_time:
                            if seq.mail_type!='not_interested':
                                state = self.pool.get('email.smtpclient').send_email( cr,  uid, smtpserver_id,
                                            email, subject.encode('utf-8'), body.encode('utf-8'), [], [('report.gs_stock_incoming_shipment',[2888])], [] )
                                cr.commit()

                                if not state:
                                    raise Exception, _('Verification failed, Please check the Server Configuration!')

                                self.pool.get('mail.sequence').write(cr,uid,[seq.id],{'state':'sent'})

                            if seq.mail_type=='not_interested' and member.not_interested==True:
                                state = self.pool.get('email.smtpclient').send_email( cr,  uid, smtpserver_id,
                                            email, subject.encode('utf-8'), body.encode('utf-8'), [], [('report.gs_stock_incoming_shipment',[2888])], [] )
                                cr.commit()

                                if not state:
                                    raise Exception, _('Verification failed, Please check the Server Configuration!')
                                self.pool.get('mail.sequence').write(cr,uid,[seq.id],{'state':'sent'})

                    to=''
        return True

    def run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
        print 'Mass Mail Scheduler Starting....'
        ids = self.search(cr, uid, [], context)
        for obj in self.browse(cr,uid,ids):
            self.send_mail(cr, uid, [obj.id])
        return True



mail_group()

class mail_group_member(osv.osv):

    def partner_id_change(self, cr, uid, ids,partner_id):
        if not partner_id:
            return {}
        partner_id = self.pool.get('res.partner').browse(cr, uid, partner_id)
        if partner_id.name:
            name=partner_id.name
        else:
            name= False
        if partner_id.address and partner_id.address[0].email:
            email=partner_id.address[0].email
        else:
            email= False
        return {'value':{'prospect': name,'email':email}}

    _name = "mail.group.member"
    _description = "Mail Group Member"
    _rec_name = "partner_id"
    _columns = {
                'partner_id': fields.many2one('res.partner', 'Member',),
                'prospect':fields.char('Prospect',size=60,),
                'email':fields.char('Email',size=28,required=True),
                'not_interested':fields.boolean('Not Interested'),
                'mail_group_id': fields.many2one('mail.group', 'Mail Group', ),
                }
    _sql_constraints = [
        ('email_uniq', 'unique (mail_group_id,email)', 'The email must be unique per group !')
    ]
mail_group_member()

class mail_sequence(osv.osv):
    _name = "mail.sequence"
    _description = "Mail Sequence"
    _rec_name = "mail_type"
    _columns = {
                'seq_id': fields.integer('Sequence',),
                'mail_type': fields.selection([('interested','Prospect Interested'),('not_interested','Prospect Not Interested'),],'Type', required=True,),
                'template_id': fields.many2one('email.smtpclient.email.template', 'Template',required=True),
                'next_call':fields.date('Next Call',),
                'state':fields.selection([('draft','Draft'),('sent','Sent'),('pending','Pending'),],'State', readonly=True,),
                'mail_group_id': fields.many2one('mail.group', 'Mail Group', ),
                }
    _defaults = {
        'state': lambda *a: 'draft',
    }
mail_sequence()
